<?php

/*
 * Author: Nguyen Hai Nam
 * Module: Product_AllModule
 * Desc	: Introduce pick.vn and sidle pic
 * Date	: 12/12/2011
 */

class Product_AllModule extends Pick_Core_Module {

    public $authentication = 1;

    function Product_AllModule() {

        parent::Pick_Core_Module();
        $this->theme = "admin";
        # Languages
        $languages = new Pick_Core_Languages();
        $objectLanguages = $languages->getObjects(1, 'status = 1', array('position' => 'ASC'), '');
        if ($objectLanguages) {
            $objectLanguages = $objectLanguages['data'];
        }#endif
        $this->template->assign("objectLanguages", $objectLanguages);

        // Get Path for this module
        $this->template->assign('arrayParentPath', $this->getArrayParentPath());
    }

    public function getContent() {

        $act = $this->request->element('act', "list");
        $this->template->assign('act', $act);
        if ($act == "position") {
            $productcategory = new Pick_Dao_ProductCategory();
            $oId = $this->request->element('id', 0);
            $val = $this->request->element('val', '');
            $arrData = array('position' => $val);
            echo $productcategory->updateData($arrData, $oId);
            die;
        }
        if ($act == "add") {
            $this->addAction();
        } else {
            $this->listAction();
        }
    }

    public function listAction() {

        $productcategory = new Pick_Dao_ProductCategory();
        $news = new Pick_Dao_Product();
        $actions = new Pick_Core_Actions();

        $actions->setInfoAction($news, $this->request);

        $items_per_pages = DEFAULT_ADMIN_ROWS_PER_PAGE;
        $infoText = '';
        $infoClass = 'infoText';

        # Read parameters from request
        $pid = $this->request->element('pid', '');
        $searchTerms = $this->request->element('searchTerms', '');
        $searchStatus = $this->request->element('searchStatus', '-1');
        $searchCategory = $this->request->element('searchCategory', '-1');
        $page = $this->request->element('page', 1);
        $orderBy = $this->request->element('orderBy', 'date_created');
        $orderDir = $this->request->element('orderDir', 'DESC');
        $defaultName = $this->lang . "_name";

        # Menu
        $menu = $this->getMenu();

        # Lay menu cap cao nhat
        $objectMenuProduct = $productcategory->getSubCategory(0);

        # Build search condition
        if (!$pid && isset($objectMenuProduct[0]))
            $pid = $objectMenuProduct[0]->getField('id');

        # Control plus action
        $plus = $this->request->element('plus', '');
        if ($plus) {
            $actions->auto($plus, "cid IN(" . implode(',', $productcategory->getIdSubCategoryALL($pid, 1)) . ")");
            $infoText = $actions->getInfoAction();
            $infoClass = "errorText";
        }

        $searchCond = "cid IN(" . implode(',', $productcategory->getIdSubCategoryALL($pid, 1)) . ")";
        if ($searchStatus != '-1')
            $searchCond .= " AND status = '$searchStatus'";
        if ($searchCategory != '-1') {
            $productCategorySub = new ProductCategorySub();
            $arrIDProduct = $productCategorySub->getArrIdProducts($searchCategory);
            if (count($arrIDProduct))
                $searchCond .= " AND id IN(" . implode(",", $arrIDProduct) . ")";
        }
        if ($searchTerms)
            $searchCond .= " AND (" . $defaultName . " LIKE '%" . $searchTerms . "%' OR slug LIKE '%" . $searchTerms . "%' )";

        # Get all news object and pass to template
        $listObjects = $news->getObjects($page, $searchCond, array($orderBy => $orderDir), $items_per_pages);

        # Generate status combobox for Search form
        $listStatus = optionStatus($searchStatus);

        # Generate category combox for search form
        $listCategory = $productcategory->optionAllCategories($pid, $searchCategory);

        # Pass some variables to template
        $this->template->assign('pid', $pid);
        $this->template->assign('page', $page);
        $this->template->assign('menu', $menu);
        $this->template->assign('listStatus', $listStatus);
        $this->template->assign('listCategory', $listCategory);
        $this->template->assign('listObjects', $listObjects);
        $this->template->assign('searchTerms', $searchTerms);
        $this->template->assign('searchStatus', $searchStatus);
        $this->template->assign('orderBy', $orderBy);
        $this->template->assign('orderDir', $orderDir);
        $this->template->assign('infoText', $infoText);
        $this->template->assign('infoClass', $infoClass);
    }

    public function addAction() {

        $upload = new Pick_Core_Upload();
        $productcategory = new Pick_Dao_ProductCategory();
        $location = new Pick_Dao_Location();
        $relax = new Pick_Dao_Relax();
        $news = new Pick_Dao_Product();
        $objectInfo = new Pick_Dao_ProductInfo();
        $textfilter = new Pick_Data_TextFilter();

        $plus = $this->request->element('plus', '');
        $oId = $this->request->element('oId', '0');
        $pid = $this->request->element('pid', '-1');
        $infoText = "";
        $infoClass = "";

        # Menu
        $menu = $this->getMenu();

        # Get Infor image
        $sizeimages = array();
        $objectPostCategory = $productcategory->getObject($pid);
        if (is_object($objectPostCategory)) {
            $sizeimages = unserialize($objectPostCategory->getField('properties'));
            if ($sizeimages["wavatar"] == "" && $sizeimages["wmedium"] == "" && $sizeimages["wbig"] == "") {
                $sizeimages["wavatar"] = $this->info->getField('wavatar');
                $sizeimages["havatar"] = $this->info->getField('havatar');
                $sizeimages["wmedium"] = $this->info->getField('wmedium');
                $sizeimages["hmedium"] = $this->info->getField('hmedium');
                $sizeimages["wbig"] = $this->info->getField('wbig');
                $sizeimages["hbig"] = $this->info->getField('hbig');
            }
        }
        $this->template->assign("objectPostCategory", $objectPostCategory);
        $this->template->assign("sizeimages", $sizeimages);

        # Read parameters from request
        $arrayFieldFromMySQL = $news->getListFields();
        $object = $news->getObject($oId);
        if (is_object($object) && $this->request->post('plus') == "") {
            foreach ($arrayFieldFromMySQL as $fieldName) {
                $fields[$fieldName] = $object->getField($fieldName);
            }#endforeach	
        } else {
            foreach ($arrayFieldFromMySQL as $fieldName) {
                $fields[$fieldName] = $this->request->element($fieldName, '');
            }#endforeach
        }

        # Modify item of array
        $nameDefault = $this->lang . "_name";
        $addressDefault = $this->lang . "_address";
        $arrayAvatar = '';
        $arraycid = array();
        if (is_object($object)) {
            $arraycid = $arraycid = $this->request->element('arraycid', $object->getArraySubCategory());
            if ($object->getField('avatar')) {
                $arrayAvatar = $this->request->element('arrayavatar', unserialize($object->getField('avatar')));
            }
            $fields['date_created'] = format_date($fields['date_created'], '-');
        } else {
            $arraycid = $this->request->element('arraycid', '');
        }
        $this->template->assign("arrayavatar", $arrayAvatar);
        $this->template->assign("arraycid", $arraycid);

        $fields['userid'] = $_SESSION['userId'];
        $fields['typeid'] = 2;
        $fields['slug'] = $textfilter->urlize($this->request->element('slug', $fields[$nameDefault]), false, '-');
        $background = isset($_FILES['background']) ? $_FILES['background'] : '';
        $files1 = isset($_FILES['files1']) ? $_FILES['files1'] : '';
        $files2 = isset($_FILES['files2']) ? $_FILES['files2'] : '';

        # Put data into object
        $objectInfo->setArrayField($fields);
        $this->template->assign("objectInfo", $objectInfo);

        # Truy du lieu qua template
        $listStatus = optionStatus($fields['status']);
        $this->template->assign("listStatus", $listStatus);
        $listCategories = $productcategory->optionAllCategories($pid, $objectInfo->getField('cid'), $this->lang, array('position' => 'ASC'), 0, 4);
        $this->template->assign("listCategories", $listCategories);
        $listLocation = $location->optionAllCategories(0, $objectInfo->getField('location'), $this->lang);
        $this->template->assign("listLocation", $listLocation);
        $subCategories = $productcategory->getSubCategory($pid);
        $this->template->assign("subCategories", $subCategories);
        $arrRelax = $relax->getSubCategory(0);
        $this->template->assign("arrRelax", $arrRelax);
        $this->template->assign('addressDefault', $fields[$addressDefault]);

        foreach ($arrayFieldFromMySQL as $fieldName) {
            $this->template->assign($fieldName, $fields[$fieldName]);
        }#endforeach
        # Process data into database
        $objectInfo->setField('date_created', format_date($fields['date_created'], '/'));

        # Begin process data
        if ($_POST && $plus == 'saveItem') {

            # Validation
            $validate = new Pick_Data_Validate();
            $validatemess = $this->validateData($this->request, $validate);

            if ($validatemess == '') {
                /* Test if it's exists then can't add theme more'' */
                $objectNews = "";

                if ($oId < 0) {
                    $objectNews = $news->checkDataExits($fields);
                }

                if (is_object($objectNews)) {
                    $infoText = $this->l('item_saved_error');
                    $infoClass = "InfoText";
                } else {
                    /* Duong dan */
                    $backgroundbath = ROOT_PATH . "/upload/images/";
                    $is_Delete_Backgournd = $this->request->post('background_del');
                    if($is_Delete_Backgournd){
                        @unlink($backgroundbath.$objectInfo->getField('background'));
                    }
                    $upload = new Pick_Core_Upload($background);
                    $background = $upload->moveImage($backgroundbath, $objectInfo->getField('background'));
                    $objectInfo->setField('background', $background);
                    unset($upload);
                    unset($background);
                    /* Duong dan */
                    $filebath = ROOT_PATH . "/upload/files/";
                    
                    $upload = new Pick_Core_Upload($files1);
                    $files1 = $upload->moveFile($filebath, $objectInfo->getField('files1'));
                    $objectInfo->setField('files1', $files1);
                    unset($upload);
                    unset($files1);

                    $upload = new Pick_Core_Upload($files2);
                    $files2 = $upload->moveFile($filebath, $objectInfo->getField('files2'));
                    $objectInfo->setField('files2', $files2);
                    unset($upload);
                    unset($files2);

                    if ($oId == 'NULL')
                        $oId = 0;

                    $ok = $news->updateData($objectInfo->getArrayField(), $oId);
                    $infoText = $validatemess;
                    if ($ok) {
                        $infoText = $this->l('item_save_ok');
                        $infoClass = "InfoText";
                        $oId = $oId ? $oId : mysql_insert_id();
                        if ($oId) {
                            $productcategorysub = new Pick_Dao_ProductCategorySub();
                            // Add default category for this product if client don't checked on frame category
                            if ($arraycid == "")
                                $arraycid = array($objectInfo->getField('cid'));
                            // Save array subid into database
                            $productcategorysub->saveCategorySubForProduct($oId, $arraycid);
                        }
                    }
                }
            }else {
                $infoText = $this->l('error') . "<br />" . $validatemess;
                $infoClass = "infoText";
            }
        }
        $this->template->assign("oId", $oId);
        $this->template->assign("menu", $menu);
        $this->template->assign("infoText", $infoText);
        $this->template->assign("infoClass", $infoClass);
    }

    function getMenu() {

        $productcategory = new Pick_Dao_ProductCategory();

        # Lấy thông tin chuyen muc từ $pid;
        $pid = $this->request->element('pid');

        # Lay menu cap cao nhat
        $objectMenuProduct = $productcategory->getSubCategory(0);

        # Build search condition
        if (!$pid && isset($objectMenuProduct[0]))
            $pid = $objectMenuProduct[0]->getField('id');

        $objParentMenu = $productcategory->getParrentRoot($pid);

        $this->template->assign("pid", $pid);
        $this->template->assign("objParentMenu", $objParentMenu);
        $this->template->assign('objectMenuProduct', $objectMenuProduct);

        return $this->displayPart('product_all/menu');
    }

    function validateData($request, $validate) {
        $infoText = '';
        $infoText .= $validate->validStatus($this->l('category'), $request->element('cid'));
        $infoText .= $validate->validStatus($this->l('status'), $request->element('status'));
        $infoText .= $validate->validString($this->l('code'), $request->element("code"));
        return $infoText;
    }

}